/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.chain2.web.servlet;


import java.io.BufferedReader;
import java.io.IOException;
import java.security.Principal;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.apache.commons.chain2.web.MockEnumeration;
import org.apache.commons.chain2.web.MockPrincipal;


/**
 *  Mock Object for HttpServletRequest (Version 2.3)
 */
public class MockHttpServletRequest implements HttpServletRequest {

    /**
     * constructor
     */
    public MockHttpServletRequest() {
        super();
    }

    /**
     * @param session HttpSession
     */
    public MockHttpServletRequest(HttpSession session) {
        super();
        setHttpSession(session);
    }

    /**
     * @param contextPath String
     * @param servletPath String
     * @param pathInfo String
     * @param queryString String
     */
    public MockHttpServletRequest(String contextPath, String servletPath,
                                  String pathInfo, String queryString) {
        super();
        setPathElements(contextPath, servletPath, pathInfo, queryString);
    }

    /**
     * @param contextPath String
     * @param servletPath String
     * @param pathInfo String
     * @param queryString String
     * @param session HttpSession
     */
    public MockHttpServletRequest(String contextPath, String servletPath,
                                  String pathInfo, String queryString,
                                  HttpSession session) {
        super();
        setPathElements(contextPath, servletPath, pathInfo, queryString);
        setHttpSession(session);
    }



    protected Map<String, Object> attributes = new HashMap<>();
    protected String contextPath = null;
    protected Map<String, String[]> headers = new HashMap<>();
    protected Cookie[] cookies = {};
    protected Locale locale = null;
    protected Map<String, String[]> parameters = new HashMap<>();
    protected String pathInfo = null;
    protected Principal principal = null;
    protected String queryString = null;
    protected String servletPath = null;
    protected HttpSession session = null;


    // --------------------------------------------------------- Public Methods

    /**
     * @param name String
     * @param value String
     */
    public void addHeader(String name, String value) {
        String values[] = headers.get(name);
        if (values == null) {
            String results[] = new String[] { value };
            headers.put(name, results);
            return;
        }
        String results[] = new String[values.length + 1];
        System.arraycopy(values, 0, results, 0, values.length);
        results[values.length] = value;
        headers.put(name, results);
    }

    /**
     * @param name String
     * @param value String
     */
    public void addParameter(String name, String value) {
        String values[] = parameters.get(name);
        if (values == null) {
            String results[] = new String[] { value };
            parameters.put(name, results);
            return;
        }
        String results[] = new String[values.length + 1];
        System.arraycopy(values, 0, results, 0, values.length);
        results[values.length] = value;
        parameters.put(name, results);
    }

    /**
     * @param name String
     * @param value String
     */
    public void addCookie(String name, String value) {
        addCookie(new Cookie(name, value));
    }

    /**
     * @param cookie Cookie
     */
    public void addCookie(Cookie cookie) {
        Cookie[] newValues = new Cookie[cookies.length + 1];
        System.arraycopy(cookies, 0, newValues, 0, cookies.length);
        cookies = newValues;
        cookies[cookies.length - 1] = cookie;
    }

    /**
     * @param session HttpSession
     */
    public void setHttpSession(HttpSession session) {
        this.session = session;
    }

    /**
     * @param locale Locale
     */
    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    /**
     * @param contextPath String
     * @param servletPath String
     * @param pathInfo String
     * @param queryString String
     */
    public void setPathElements(String contextPath, String servletPath,
                                String pathInfo, String queryString) {

        this.contextPath = contextPath;
        this.servletPath = servletPath;
        this.pathInfo = pathInfo;
        this.queryString = queryString;

    }

    /**
     * @param principal Principal
     */
    public void setUserPrincipal(Principal principal) {
        this.principal = principal;
    }



    // --------------------------------------------- HttpServletRequest Methods

    /**
     * @see javax.servlet.http.HttpServletRequest#getAuthType()
     */
    @Override public String getAuthType() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getContextPath()
     */
    @Override public String getContextPath() {
        return (contextPath);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getCookies()
     */
    @Override public Cookie[] getCookies() {
        return cookies.clone();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
     */
    @Override public long getDateHeader(String name) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
     */
    @Override public String getHeader(String name) {
        String values[] = headers.get(name);
        if (values != null) {
            return (values[0]);
        }
        return (null);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getHeaderNames()
     */
    @Override public Enumeration<String> getHeaderNames() {
        return (new MockEnumeration<>(headers.keySet().iterator()));
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
     */
    @Override public Enumeration<String> getHeaders(String name) {
        String headers[] = this.headers.get(name);
        if (headers == null) {
            headers = new String[0];
        }
        return (new MockEnumeration<>(Arrays.asList(headers).iterator()));
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
     */
    @Override public int getIntHeader(String name) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getMethod()
     */
    @Override public String getMethod() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getPathInfo()
     */
    @Override public String getPathInfo() {
        return (pathInfo);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getPathTranslated()
     */
    @Override public String getPathTranslated() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getQueryString()
     */
    @Override public String getQueryString() {
        return (queryString);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getRemoteUser()
     */
    @Override public String getRemoteUser() {
        if (principal != null) {
            return (principal.getName());
        }
        return (null);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getRequestedSessionId()
     */
    @Override public String getRequestedSessionId() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getRequestURI()
     */
    @Override public String getRequestURI() {
        StringBuilder sb = new StringBuilder();
        if (contextPath != null) {
            sb.append(contextPath);
        }
        if (servletPath != null) {
            sb.append(servletPath);
        }
        if (pathInfo != null) {
            sb.append(pathInfo);
        }
        if (sb.length() > 0) {
            return (sb.toString());
        }
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getRequestURL()
     */
    @Override public StringBuffer getRequestURL() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getServletPath()
     */
    @Override public String getServletPath() {
        return (servletPath);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getSession()
     */
    @Override public HttpSession getSession() {
        return (getSession(true));
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getSession(boolean)
     */
    @Override public HttpSession getSession(boolean create) {
        if (create && (session == null)) {
            throw new UnsupportedOperationException();
        }
        return (session);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getUserPrincipal()
     */
    @Override public Principal getUserPrincipal() {
        return (principal);
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromCookie()
     */
    @Override public boolean isRequestedSessionIdFromCookie() {
        throw new UnsupportedOperationException();
    }

    /**
     * @deprecated deprecated
     */
    @Deprecated
    @Override public boolean isRequestedSessionIdFromUrl() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdFromURL()
     */
    @Override public boolean isRequestedSessionIdFromURL() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()
     */
    @Override public boolean isRequestedSessionIdValid() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#isUserInRole(java.lang.String)
     */
    @Override public boolean isUserInRole(String role) {
        if ((principal != null) && (principal instanceof MockPrincipal)) {
            return (((MockPrincipal) principal).isUserInRole(role));
        }
        return (false);
    }


    // ------------------------------------------------- ServletRequest Methods

    /**
     * @see javax.servlet.ServletRequest#getAttribute(java.lang.String)
     */
    @Override public Object getAttribute(String name) {
        return (attributes.get(name));
    }

    /**
     * @see javax.servlet.ServletRequest#getAttributeNames()
     */
    @Override public Enumeration<String> getAttributeNames() {
        return (new MockEnumeration<>(attributes.keySet().iterator()));
    }

    /**
     * @see javax.servlet.ServletRequest#getCharacterEncoding()
     */
    @Override public String getCharacterEncoding() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getContentLength()
     */
    @Override public int getContentLength() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getContentType()
     */
    @Override public String getContentType() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getInputStream()
     */
    @Override public ServletInputStream getInputStream() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getLocale()
     */
    @Override public Locale getLocale() {
        return (locale);
    }

    /**
     * @see javax.servlet.ServletRequest#getLocales()
     */
    @Override public Enumeration<Locale> getLocales() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getLocalAddr()
     */
    @Override public String getLocalAddr() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getLocalName()
     */
    @Override public String getLocalName() {
    throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getLocalPort()
     */
    @Override public int getLocalPort() {
    throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getParameter(java.lang.String)
     */
    @Override public String getParameter(String name) {
        String values[] = parameters.get(name);
        if (values != null) {
            return (values[0]);
        }
        return (null);
    }

    /**
     * @see javax.servlet.ServletRequest#getParameterMap()
     */
    @Override public Map<String, String[]> getParameterMap() {
        return (parameters);
    }

    /**
     * @see javax.servlet.ServletRequest#getParameterNames()
     */
    @Override public Enumeration<String> getParameterNames() {
        return (new MockEnumeration<>(parameters.keySet().iterator()));
    }

    /**
     * @see javax.servlet.ServletRequest#getParameterValues(java.lang.String)
     */
    @Override public String[] getParameterValues(String name) {
        return parameters.get(name);
    }

    /**
     * @see javax.servlet.ServletRequest#getProtocol()
     */
    @Override public String getProtocol() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getReader()
     */
    @Override public BufferedReader getReader() {
        throw new UnsupportedOperationException();
    }

    /**
     * @deprecated deprecated
     */
    @Deprecated
    @Override public String getRealPath(String path) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRemoteAddr()
     */
    @Override public String getRemoteAddr() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRemoteHost()
     */
    @Override public String getRemoteHost() {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRemotePort()
     */
    @Override public int getRemotePort() {
    throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getRequestDispatcher(java.lang.String)
     */
    @Override public RequestDispatcher getRequestDispatcher(String path) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getScheme()
     */
    @Override public String getScheme() {
        return ("http");
    }

    /**
     * @see javax.servlet.ServletRequest#getServerName()
     */
    @Override public String getServerName() {
        return ("localhost");
    }

    /**
     * @see javax.servlet.ServletRequest#getServerPort()
     */
    @Override public int getServerPort() {
        return (8080);
    }

    /**
     * @see javax.servlet.ServletRequest#isSecure()
     */
    @Override public boolean isSecure() {
        return (false);
    }

    /**
     * @see javax.servlet.ServletRequest#removeAttribute(java.lang.String)
     */
    @Override public void removeAttribute(String name) {
        attributes.remove(name);
    }

    /**
     * @see javax.servlet.ServletRequest#setAttribute(java.lang.String, java.lang.Object)
     */
    @Override public void setAttribute(String name, Object value) {
        if (value == null) {
            attributes.remove(name);
        } else {
            attributes.put(name, value);
        }
    }

    /**
     * @see javax.servlet.ServletRequest#setCharacterEncoding(java.lang.String)
     */
    @Override public void setCharacterEncoding(String name) {
        throw new UnsupportedOperationException();
    }

    /**
     * @see javax.servlet.ServletRequest#getAsyncContext()
     */
    @Override
    public AsyncContext getAsyncContext() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#getDispatcherType()
     */
    @Override
    public DispatcherType getDispatcherType() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#getServletContext()
     */
    @Override
    public ServletContext getServletContext() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#isAsyncStarted()
     */
    @Override
    public boolean isAsyncStarted() {
        return false;
    }

    /**
     * @see javax.servlet.ServletRequest#isAsyncSupported()
     */
    @Override
    public boolean isAsyncSupported() {
        return false;
    }

    /**
     * @see javax.servlet.ServletRequest#startAsync()
     */
    @Override
    public AsyncContext startAsync() {
        return null;
    }

    /**
     * @see javax.servlet.ServletRequest#startAsync(
     * javax.servlet.ServletRequest, javax.servlet.ServletResponse)
     */
    @Override
    public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) {
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#authenticate(javax.servlet.http.HttpServletResponse)
     */
    @Override
    public boolean authenticate(HttpServletResponse arg0) throws IOException,
            ServletException {
        return false;
    }


    /**
     * @see javax.servlet.http.HttpServletRequest#getPart(java.lang.String)
     */
    @Override
    public Part getPart(String arg0) throws IOException, IllegalStateException,
            ServletException {
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#getParts()
     */
    @Override
    public Collection<Part> getParts() throws IOException,
            IllegalStateException, ServletException {
        return null;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#login(java.lang.String, java.lang.String)
     */
    @Override
    public void login(String arg0, String arg1) throws ServletException {
        return;
    }

    /**
     * @see javax.servlet.http.HttpServletRequest#logout()
     */
    @Override
    public void logout() throws ServletException {
        return;
    }

}
